<?php

/*
 * Copyright (C) 2014 University of Pittsburgh
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once('util/Constants.inc');
require_once('AbstractDAO.inc');

class ReferenceTableDAO extends AbstractDAO {
  
  private $table_name = NULL;
  
  public function __construct() {
    parent::__construct(); 
    unset($this->table_name);
  }
  
  public function set_table($ref_table_code = 0) {
    $found = false;
    foreach(Constants::$reference_table_names as $key => $value) {
      if($ref_table_code == $key) {
        $found = true;
        break;
      }
    }
    
    if(!$found) {
      $this->error_code = Constants::ERR_CODE_INV_TABLE_CODE;
      $this->error_info = Constants::ERR_MSG_INV_TABLE_CODE;
      unset($this->table_name);
    } else {
      $this->table_name = Constants::$reference_table_names[$ref_table_code];
    }
   
  }
	  	
  public function get_table_data_as_array() {
    
    if(!$this->table_name) {
      $this->error_code = Constants::ERR_CODE_NO_REF_TABLE;
      $this->error_info = Constants::ERR_MSG_NO_REF_TABLE;
      return NULL;
    }
    
    $dbh = new PDO(Constants::DB_NAME, Constants::DB_USERNAME, Constants::DB_PASSWORD);
    $stmt = $dbh->prepare("SELECT * FROM " . $this->table_name);
    
    if($stmt) {       
      
      if($stmt->execute()) {
        
        $ret_val = array();
        
        foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $assoc_arr) {
          $ref_code = $assoc_arr['ref_code'];
          $ref_text = $assoc_arr['ref_text'];
          $ret_val[$ref_code] = $ref_text;
        }
        
        return $ret_val;
        
      } else {
        $this->errorCode = $stmt->errorCode();
        $this->errorInfo = $stmt->errorInfo();
        unset($dbh);
        return NULL;
      }
    } else {
      $this->errorCode = $stmt->errorCode();
      $this->errorInfo = $stmt->errorInfo();
      unset($dbh);
      return NULL;
    }
  }   
}

?>